package com.attilax.dataService;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;

import aaaCfg.IocX;
import aaaCfg.IocX4sqlite;



//
//import com.attilax.core;
import com.attilax.anno.Inj;
import com.attilax.db.DBX;
import com.attilax.io.filex;
import com.attilax.ioc.IocUtilV2;
import com.attilax.ioc.IocXq214;
import com.attilax.json.AtiJson;
import com.attilax.lang.Global;
import com.attilax.lang.Trigger;
import com.attilax.lbs.futureT2;
import com.attilax.net.requestImp;
import com.attilax.reflect.MethodUtils;
import com.attilax.sql.DbMetaService;
import com.attilax.sql.SqlSecuryAnalyzer;
import com.attilax.sql.SqlService;
import com.attilax.urldsl.DslUtil;
import com.attilax.urldsl.UrlDsl2SqlStoreService;
import com.attilax.user.NotLoginEx;
import com.attilax.web.ReqX;
import com.attilax.web.UrlX;
import com.google.inject.Inject;

/**
 * com.attilax.dataService.DataService
 * 
 * @author Administrator
 *
 */


public class DataServiceV2 extends DataService {
	
	public static void main(String[] args)   {
		System.out.println("00");
		System.setProperty("prj","jobus");//指明是运行的哪个项目
		requestImp ri=new requestImp();
		ri.setParam("$op", "i");
		ri.setParam("$table", "sid");
		ri.setParam("col3", "vvv");
		Global.req.set(ri);
		DataService dx = IocUtilV2.getBean(DataServiceV2.class);
		Object rows = dx.exe();
		System.out.println( AtiJson.toJson (rows));
		
		
//		String url="$trigger=aaaCfg.DataMapper4vod&$triggerPos=after";
//		Map m=UrlX.getHeader_from_QueryStr(url);
//		
//		ri.setParam("$mainCfg", "aaaCfg.IocX4sqlite");
//		ri.setParam("$op", "select");
//		ri.setParam("$table", "hitv");
//		ri.setParam("$where" , " genre like '%动作%' limit 10000 ");
//	
//	//	ri.setParamMap(m);
//		Global.req.set(ri);
//		
//		Global.mainCfg.set("aaaCfg.IocX4sqlite");
//		DataService dx = IocX4sqlite.getBean(DataService.class);
//		Object rows = dx.exe();
//		
//		//System.out.println( AtiJson.toJson (rows));
//		/*
//		 * 	"posterPicString":"死亡飞车/死亡飞车-poster.jpg",
//		"fanartPicString":"死亡飞车/死亡飞车-fanart.jpg",
//		 * */
//		List<Map> li=(List<Map>) rows;
//		System.out.println( li.size() );
//		//ExecutorService fixedThreadPool = Executors.newFixedThreadPool(50);
//		for (Map map : li) {
//			
//			FutureTask<String> fut=new FutureTask(new Callable<String>() {
//
//				@Override
//				public String call() throws Exception {
//					copyFile((String) map.get("fanartPicString"));
//					copyFile((String) map.get("posterPicString"));
//					return null;
//				}
//			}) ;
//			//fixedThreadPool.submit(fut);
//			core.submit(fut, "fut");
//			core.newThread(new Runnable() {
//				
//				@Override
//				public void run() {
//					 
//					try {
//						System.out.println(fut.get(7, TimeUnit.SECONDS));
//					} catch (InterruptedException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (ExecutionException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					} catch (TimeoutException e) {
//						  fut.cancel(true);
//						e.printStackTrace();
//					}
//				}
//			}, "threadName");
//			Runnable runnable = new Runnable() {
//				public void run() {
//					 
//						copyFile((String) map.get("fanartPicString"));
//						copyFile((String) map.get("posterPicString"));
//					 
//				}
//
//			};
//		//	fixedThreadPool.execute(runnable);
//		}
//		
		System.out.println("--f");
		
	}
	public static int notExistCount=0;
	private static void copyFile(String pathx)   {
		try {
			System.out.println(" proce is ing:"+pathx);
			String path="z:\\"+pathx;
			String path_noDsk=path.substring(3);
			String new_path="f:\\0localImgX\\"+path_noDsk;
			filex.createAllPath(new_path);
			File file = new File(path);
			if(new File(new_path).exists())
				return;
			if(!file.exists())
			{
				notExistCount++;
				System.out.println(" not exist count:"+notExistCount);
				System.out.println(" file not exist:"+path);
				return;
			}
			if(new File(new_path).exists())
				return;
			System.out.println("  coopy "+path +">>>"+ new_path);
			FileUtils.copyFile(file, new File(new_path));
		} catch (Exception e) {
			System.out.println(pathx+e.getMessage());
		}
		
	}
	
	
	  @Inject
	protected
	 SqlService sqlSrv;
	//  @Inject
	//  DBX dbx;
	  
	 public static void main2(String[] args) {
		System.out.println("--");
		
		requestImp ri=new requestImp();
		ri.setParam("$table", "hitv");
		ri.setParam("$where", " genre like '%动画%'");
		Global.req.set(ri);
		DataServiceV2 ds=IocXq214.getBean(DataServiceV2.class);
		Object rows = ds. exe();
		System.out.println( AtiJson.toJson( rows));
	}
//$storeEngiee=folderAsRow  
	public Object exe() {

		 
		HttpServletRequest req = Global.req.get();
		
		String table=getTable(req);
		if(table.trim().startsWith("update"))
		{
			String sql=table.trim();
		   new SqlSecuryAnalyzer().parse4upOrDel(sql);
			return sqlSrv.executeUpdate(req.getParameter("$tb"));
		}
		String tableType =getTableType(req);
		if(tableTypeIsSql(tableType))   //def is table type
			
			return sqlSrv.executeQuery(table);
		tkSrv.setModule(req.getParameter("$utype") + "Mod");
		if(req.getParameter("$utype")==null)
			tkSrv.setModule("userMod");
		//trigger pos:before
		if (req.getParameter("$trigger") != null  && req.getParameter("$triggerPos")==null ) // p319
		{
			String tiggerName = req.getParameter("$trigger");
			Object trigger = IocXq214.getBean(tiggerName);
			this.trigr = (Trigger) trigger;
		}
		
		//q46
		Global.dbName.set("$defdb");
		if(req.getParameter("$db")!=null)
		{
			Global.dbName.set(req.getParameter("$db"));
		}

		@SuppressWarnings("rawtypes")
		Map m = ReqX.toMap(req);
		processTable(m);
		processOp(m);
		
		processPreVar(req, m);
		// fld fun
		DslUtil.appFldFun(m);
		if (trigr != null)
			trigr.exec(m);
		if(m.get("$storeEngiee")!=null)
			if(m.get("$storeEngiee").equals("folderAsRow"))
					return new folderAsRowDataService().exe(m);
				
		metaSvr.createNewCol(m);	   
		Object rows = dsl2sqlV2q326(m);
		if(m.get("$trigger")!=null && m.get("$triggerPos").equals("after") )
		{
		   Trigger o=  	IocXq214.getBean(m.get("$trigger").toString());
		   rows=  o.exec(rows);
		}
		return rows;

	}
	@Inject
	DbMetaService metaSvr;
	private void processPreVar(HttpServletRequest req, Map m) {
		Set<String> st = m.keySet();
		for (String k : st) {
			if (m.get(k).equals("$cur_uid")) {
				String getuid = tkSrv.getuid(req);
				if (StringUtils.isEmpty(getuid))
					throw new NotLoginEx("NotLoginEx");
				m.put(k, getuid);
			}
			
			if (m.get(k).equals("$uid")) {
				String getuid = tkSrv.getuid(req);
				if (StringUtils.isEmpty(getuid))
					throw new NotLoginEx("NotLoginEx");
				m.put(k, getuid);
			}
			if (m.get(k).toString().equals("$uuid")) {
				m.put(k, filex.getUUidName());
			}
		}
		// fld fun
		DslUtil.appFldFun(m);
		if (trigr != null)
			trigr.exec(m);
//		if(m.get("$storeEngiee")!=null)
//			if(m.get("$storeEngiee").equals("folderAsRow"))
//					return new folderAsRowDataService().exe(m);
				
				
//		Object rows = dsl2sqlV2q326(m);
//		if(m.get("$trigger")!=null && m.get("$triggerPos").equals("after") )
//		{
//		   Trigger o=  	IocXq214.getBean(m.get("$trigger").toString());
//		   rows=  o.exec(rows);
//		}
//		return rows;
		 

	}

	/**
	attilax    2016年4月19日  下午5:40:44
	 * @param table
	 */
	private void checkLogin(String sql) {
		if(sql.contains("$uid$"))
		if(StringUtils.isEmpty(tkSrv.getuid()))
			throw new NotLoginEx("");
		
	}
	/**
attilax    2016年4月19日  下午5:40:20
 * @param req
 */
private void checkLogin(HttpServletRequest req) {
	// TODO Auto-generated method stub
	
}


	protected void processOp(Map m) {
	String op = getOp(m);
	if (op.equals("i"))
		m.put("$op", "insert");
	if(op==null)
		m.put("$op","select");
	if(op.equals("q"))
		m.put("$op","select");
	
}
protected void processTable(Map m) {
	if (m.get("$table") == null)
		m.put("$table", m.get("$tb"));
}

	private boolean tableTypeIsSql(String tableType) {
	if(	tableType!=null && tableType.equals("sq"))
		return true;
	if(	tableType!=null && tableType.equals("sql"))
		return true;
		return false;
	}
	private String getOp(Map m) {
		return	(String) m.get("$op");
	//./return null;
}
	private String getTableType(HttpServletRequest req) {
		if( !StringUtils.isEmpty( req.getParameter("$tbtype")))
			return req.getParameter("$tbtype");
		if( !StringUtils.isEmpty( req.getParameter("$tabletype")))
			return req.getParameter("$tabletype");
	return null;
}
	/**
	attilax    2016年4月12日  下午10:26:51
	 * @param req
	 * @return
	 */
	private String getTable(HttpServletRequest req) {
		if(req.getParameter("$tb")!=null)
			return req.getParameter("$tb");
		if(req.getParameter("$table")!=null)
			return req.getParameter("$table");
		 
		return null;
	}
	//com.attilax.sql.Dsl2sqlService@4dc8d72b
	private Object dsl2sqlV2q326(Map m) {
		String sql = d2sSrv.dsl2sql(m);
		sql=processPreVar4sql(sql);
		System.out.println(sql);
		if (StringUtils.isEmpty(sql))
			throw new RuntimeException(
					" cant convert sql str rzt is null or empty:"+d2sSrv);
		return sqlSrv.exe(sql);
	}
	/**
	attilax    2016年4月21日  下午10:05:05
	 * @param sql
	 * @return
	 */
	private String processPreVar4sql(String sql) {
		sql = sql.replace("$uid$", tkSrv.getuid());
		return sql;
	}

}
